package com.edmendst.xmall.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.edmendst.xmall.dto.CallBackPayInFo;
import com.edmendst.xmall.dto.PaymentRequest;
import com.edmendst.xmall.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityCoreVersion;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.SpringServletContainerInitializer;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mjz
 */
@RestController
@RequestMapping("/pay")
public class PayController {

    @Value("${pay.publicKey}")
    private String PUBLIC_KEY;

    @Autowired
    private PayService payService;
//    //订单支付
//    String payOrder(String orderId, BigDecimal orderTotalAmount, String userName) throws AlipayApiException;

    /**
     * 订单支付接口
     *
     * @param paymentRequest 包含订单ID和订单总金额的请求体
     * @return 支付结果
     * @throws AlipayApiException 支付异常
     */
    @PostMapping
    public ResponseEntity<String> payOrder(@RequestBody PaymentRequest paymentRequest) throws AlipayApiException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String userName = authentication.getName();
        return payService.payOrder(paymentRequest.getOrderId(), paymentRequest.getOrderTotalAmount(), userName);
//        String result = payService.payOrder(paymentRequest.getOrderId(), paymentRequest.getOrderTotalAmount(), userName);
//        return ResponseEntity.ok(result);
//        String result = payService.payOrder(paymentRequest.getOrderId(), paymentRequest.getOrderTotalAmount(), userName);
//        // 明确指定响应类型为 HTML
//        return ResponseEntity.ok()
//                .contentType(MediaType.TEXT_HTML)
//                .body(result);
    }

    //
//    //支付回调
//    String callBackPay(CallBackPayInFo callBackPayInFo);
    @PostMapping("/callback")
    public ResponseEntity<String> callBackPay(@RequestParam Map<String, String> params) throws AlipayApiException, ParseException {
        try {
            // 所有传入参数
            System.out.println("Received Params: " + params);
            //过滤空值参数
            Map<String, String> validParams = params.entrySet().stream()
                    .filter(entry -> entry.getValue() != null && !entry.getValue().trim().isEmpty())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

            // 验签
            String signType = validParams.get("sign_type");
            boolean isValid = AlipaySignature.rsaCheckV1(
                    validParams,
                    PUBLIC_KEY,
                    "UTF-8",
                    signType
            );
            if (!isValid) {
                return ResponseEntity.badRequest().body("验签失败");
            }

            CallBackPayInFo callBackPayInFo = new CallBackPayInFo();
            callBackPayInFo.setAppId(params.get("app_id"));
            callBackPayInFo.setAuthAppId(params.get("auth_app_id"));

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // 解析为java.util.Date
            java.util.Date parsedDate = format.parse(params.get("notify_time"));
// 转换为java.sql.Date
            callBackPayInFo.setNotifyTime(new java.sql.Date(parsedDate.getTime()));

            callBackPayInFo.setNotifyType(params.get("notify_type"));
            callBackPayInFo.setNotifyId(params.get("notify_id"));
            callBackPayInFo.setSignType(params.get("sign_type"));
            callBackPayInFo.setSign(params.get("sign"));
            callBackPayInFo.setTradeNo(params.get("trade_no"));
            callBackPayInFo.setOutTradeNo(params.get("out_trade_no"));
            callBackPayInFo.setTradeStatus(params.get("trade_status"));

            BigDecimal totalAmount = params.containsKey("total_amount")
                    ? new BigDecimal(params.get("total_amount"))
                    : BigDecimal.ZERO;
            callBackPayInFo.setTotalAmount(totalAmount);

            callBackPayInFo.setReceiptAmount(new BigDecimal(params.get("receipt_amount")));
            String result = payService.callBackPay(params, callBackPayInFo); // 传递params
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("系统错误，请稍后再试");
        }
    }
}
